<template>
  <div class="ksd-upload" style="width: 100%">
    <ClientOnly>
      <template #fallback>
        <div class="border rounded bg-gray-50 flex items-center justify-center"
             style="width:94px;height:94px;">
            <k-loading show></k-loading>
        </div>
      </template>
      <n-upload
          v-model:file-list="fileList"
          :action="useFetchConfig.baseURL+'/v1/oss/upload/file'"
          :headers="useFetchConfig.headers"
          name="file"
          :data="data"
          list-type="image-card"
          :on-finish="handleUploadFinish"
          :on-error="handleUploadError"
          accept="image/png,image/jpeg,image/gif"
          :multiple="max > 1"
          :max="max"
      />
    </ClientOnly>
  </div>
</template>
<script setup>
import {
  NSpin,
  NUpload,
} from "naive-ui"
const useFetchConfig = useGetFetchOptions()
const fileList = ref([])
const props = defineProps({
  modelValue:[String,Array],
  data:{
    type:Object
  },
  max:{
    type:Number,
    default:1
  }
})
const emits = defineEmits("[update:modelValue]")

// 上传成功
const handleUploadFinish = (...e)=>{
  const { file,event } = e[0]
  const response = JSON.parse(event.target.response)
  file.url = response.data.url
  return file
}

// 上传失败
const handleUploadError = (...e)=>{
    useMessage().error("删除文件失败!")
}

// 监听fileList变化
const stopWatch = watch(()=>fileList,(newVal)=>{
  let urls = []
  newVal.value.forEach(o=>{
    if(o.status === "finished" && o.url){
      urls.push(o.url)
    }
  })
  emits("update:modelValue", props.max == 1 ? (urls[0] || "") : urls)
},{
  deep:true
})


// 初始化filelist
function initFileList(resp){
  if(resp.img){
    fileList.value =  [{
      id: resp.img,
      name: resp.img,
      status: 'finished',
      url: resp.img
    }]
  } else {
    fileList.value = props.modelValue ? props.modelValue.map(url=>{
      return {
        id: url,
        name: url,
        status: 'finished',
        url: url
      }
    }):[]
  }
}
defineExpose({
  initFileList
})

// 页面离开的时候监听
onBeforeUnmount(()=>stopWatch())
</script>
<style scoped>
.ksd-upload :deep(.n-upload-file-list.n-upload-file-list--grid){
  display: grid;
  grid-template-columns: repeat(auto-fill,100%);
  grid-gap: 8px;
  margin-top: 0;
}
.ksd-upload :deep(.n-upload-file-list .n-upload-file.n-upload-file--image-card-type){
  width: 100%;
  height: 100%;
}
</style>